import { ref } from 'vue'
import { adapter, request } from '@/request'
import { storeToRefs } from 'pinia'
import { useRegionStore } from '@/store/useRegionStore'
import type { RequestWrapper } from '@/core/interfaces/common'
import type { PhoenixPlatformEnum } from '@/core/enums/platform'
import { phoenixRegionCheckerByPost } from '@/core/api/priceSheet'
import { compact, keyBy } from 'lodash-es'
import is from '@/utils/is'

interface Params {
  keywords: string[]
}

export interface PhoenixRegionCheckResult {
  keyword: string
  device: PhoenixPlatformEnum
  regionList: string[]
  costRate?: number
}

export default function getPhoenixRegionCheckResult() {
  const service = adapter<RequestWrapper<PhoenixRegionCheckResult[]>>(request)
  const response = ref<Record<string, PhoenixRegionCheckResult>>({})
  const loading = ref(false)
  const regionStore = useRegionStore()
  const { mapRegion } = storeToRefs(regionStore)

  const fetch = (data: Params) => {
    const { url, method } = phoenixRegionCheckerByPost()
    loading.value = true
    response.value = {}

    return service({
      config: {
        baseURL: import.meta.env.VITE_PHOENIX_PLUS_URL,
        url,
        method,
        data
      },
      callback: (res) => {
        res.data.data.forEach((d) => {
          d.regionList = compact(
            d.regionList.map((pinyin) => {
              return mapRegion.value[pinyin]?.name_cn ?? ''
            })
          )
        })
        response.value = keyBy(res.data.data, (o) => {
          return `${o.keyword}|${o.device}`
        })
      },
      error: (err) => {
        if (is.error(err)) {
          console.log(err.message)
        }
      },
      done: () => {
        loading.value = false
      }
    })
  }

  return [response, fetch, loading] as const
}
